package thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/***
 * 
 * 多线程读取一个队列中的数据
 * 
 * @author dujl
 *
 */
public class RunnTest {

	private static int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;

	private static final int MAX_POOL_SIZE = CORE_POOL_SIZE * 4 < 256 ? 256 : CORE_POOL_SIZE * 4;
	public static final long KEEP_ALIVE_TIME = 5L;
	public static void main(String[] args) {
		LinkedBlockingQueue<Runnable> groupQueue = new LinkedBlockingQueue<>();
		String tioThreadName = "tio";
		ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(CORE_POOL_SIZE, CORE_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.MINUTES, groupQueue);
/*	 当请求线程数 超过LinkedBlockingQueue里设置的队列最大值时	，会自行运行下面的拒绝策略。这里没有设置队列的大小，所以不受限制，只要不超过虚拟机的内存大小
 * 一般都可以放到队列中等待核心线程（8个）去处理。
 * threadPoolExecutor.setRejectedExecutionHandler(
		new RejectedExecutionHandler(){ 
			@Override
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				// TODO Auto-generated method stub
				System.out.println("拒绝策略 = = "+r);
			}
		});*/
		SendRunnable r =  new SendRunnable(threadPoolExecutor);
		for(int i=0;i< 500;i++){
			r.addMsg(i);
			threadPoolExecutor.execute(r);
			
		}
		   System.out.println("=================="+threadPoolExecutor.getQueue().size());
/*		for(int i=0;i< 1000;i++){
			r.addMsg("msg "+i);
		}
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		threadPoolExecutor.execute(r);*/
	}
}
